<template>
  <div>
    <div v-if="this.goodList.length === 0">没有买的东西啦</div>
    <table border="1" width="700" style="border-collapse: collapse" v-else>
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" @change="ad" v-model="isa" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in goodList" :key="index">
          <th>
            <input type="checkbox" :value="item" v-model="add" @change="daa" />
            <span></span>
          </th>
          <!-- 把item传给了value 此时 add 就是list -->
          <th>{{ item.name }}</th>
          <th>{{ item.price }}</th>
          <th>
            <button @click="item.num++" :disabled="item.num === 20">+</button>
            {{ item.num }}
            <button @click="item.num++" :disabled="item.num === 1">-</button>
          </th>
          <th>{{ item.num * item.price }}</th>
          <th>
            <button @click="del(index, item.id)" @change="ad">删除</button>
          </th>
        </tr>
      </thead>
      <tbody></tbody>
      <tfoot>
        <tr>
          <td>合计:{{ sum() }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isa: false,
      add: [],
      goodList: [
        {
          id: 1,
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          id: 2,
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          id: 3,
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          id: 4,
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    daa() {
      if (this.add.length === this.goodList.length) {
        this.isa = true;
      } else {
        this.isa = false;
      }
    },
    ad() {
      if (this.isa === true) {
        this.add = this.goodList;
      } else {
        this.add = [];
      }
      this.daa();
    },
    del(index, id) {
      // this.add = this.add.filter((item) => {
      //   item.id = id;
      // });
      console.log(id);
      this.goodList.splice(index, 1);
      this.daa();
      // this.sum();
    },
    sum() {
      let num = 0;
      this.add.forEach((item) => {
        num += item.price * item.num;
      });
      return num;
    },
  },
};
</script>

<style>
</style>